package com.example.workassignback.config;

import com.example.workassignback.Interceptor.TokenInterceptor;
import com.example.workassignback.resolver.CurrentUserArgumentResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @Auther: Lai Wenhao
 * @Date: 2024/5/30 19:32
 **/
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private TokenInterceptor tokenInterceptor;

    @Autowired
    private CurrentUserArgumentResolver currentUserArgumentResolver;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册拦截器并排除特定路径
        registry.addInterceptor(tokenInterceptor)
                .excludePathPatterns("/user/login", "/user/register");
//        registry.addInterceptor(tokenInterceptor);
    }

    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")  // 允许所有路径
                .allowedOrigins("http://127.0.0.1:80","http://127.0.0.1:6655","http://127.0.0.1:9090")
                .allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE","OPTIONS"})  // 允许的HTTP方法
                .allowedHeaders("*")  // 允许所有头部
                .allowCredentials(true)  // 允许凭证（如Cookie）
                .maxAge(3600);  // 预检请求的缓存时间，单位为秒
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(currentUserArgumentResolver);
    }

}
